package com.wlw.admin.plugindemo;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import dalvik.system.PathClassLoader;

public class MainActivity extends AppCompatActivity {
    ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.image_view);
        findViewById(R.id.btn_load).setOnClickListener(v -> onLoad());
    }


    private void onLoad() {
        List<PluginBean> plugins = findAllPlugin();
        if (plugins != null && !plugins.isEmpty()) {
            for (PluginBean plugin : plugins) {
                dynamicLoadApk(plugin.pkgName);
            }
        } else {
            Toast.makeText(this, "没找到插件", Toast.LENGTH_SHORT).show();
        }
        startActivity(new Intent(this, SecondActivity.class));
    }

    private void dynamicLoadApk(String pkgName) {
        try {
            Context pluginContext = this.createPackageContext(pkgName, CONTEXT_IGNORE_SECURITY | CONTEXT_INCLUDE_CODE);
            PathClassLoader pathClassLoader = new PathClassLoader(pluginContext.getPackageResourcePath(), ClassLoader.getSystemClassLoader());
            Class<?> clazz = Class.forName(pkgName + ".R$mipmap", true, pathClassLoader);
            Field field = clazz.getDeclaredField("img_splash");
            int resourceId = field.getInt(R.mipmap.class);
            Drawable drawable = pluginContext.getResources().getDrawable(resourceId);
            if(drawable!=null){
                imageView.setImageDrawable(drawable);
            }
        } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException | PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private List<PluginBean> findAllPlugin() {
        List<PluginBean> pluginBeans = new ArrayList<>();
        PackageManager pm = getPackageManager();
        List<PackageInfo> packageInfo = pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
        for (PackageInfo info : packageInfo) {
            String pkgName = info.packageName;
            String sharedUserId = info.sharedUserId;
            if (sharedUserId != null && sharedUserId.equals("com.wlw.admin.plugin")
                    && !pkgName.equals(getPackageName())) {
                String label = pm.getApplicationLabel(info.applicationInfo).toString();
                PluginBean bean = new PluginBean(label, pkgName);
                pluginBeans.add(bean);
            }
        }
        return pluginBeans;
    }
}
